﻿using FirstDemo.Models;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FirstDemo.Controllers
{
    [Route("api/[controller]")]
    public class TodoItemsController : Controller
    {
        MySQLHelper helper = new MySQLHelper(GlobalString.MySQLString);

        /// <summary>
        /// 获取所有代办任务
        /// </summary>
        /// <returns></returns>
        // GET: api/<controller>
        [HttpGet]
        public object Get()  //获取IP
        {
            return helper.ExecSqlReader<TodoItem>("select * from TodoItem");
        }

        /// <summary>
        /// 通过Id获取单独一条代办任务
        /// </summary>
        /// <param name="id">任务Id</param>
        /// <returns></returns>
        // GET api/<controller>/5
        [HttpGet("{id}")]
        public object Get(int id)
        {
            return helper.RunProcResp<TodoItem>("SelectById", new MySqlParameter("p_id", id));
        }

        /// <summary>
        /// 增加一条代办任务
        /// </summary>
        /// <param name="value">代办任务名称</param>
        /// <returns></returns>
        // POST api/<controller>
        [HttpPost]
        public ActionResult Post(string value)
        {
            return Ok(helper.InsertOne<TodoItem>("TodoItem", new TodoItem() { Name = value }));
        }

        /// <summary>
        /// 根据Id修改一条代办任务的完成情况
        /// </summary>
        /// <param name="id">任务Id</param>
        /// <param name="value">完成情况</param>
        /// <returns></returns>
        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public ActionResult Put(int id, bool value)
        {
            return Ok(helper.UpdateById<TodoItem>("TodoItem", new TodoItem() { Id = id, IsComplete = value }));
        }

        /// <summary>
        /// 根据Id删除一条代办任务
        /// </summary>
        /// <param name="id">任务Id</param>
        /// <returns></returns>
        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete(int id)
        {
            return Ok(await helper.DeleteByIdAsync(id, "TodoItem"));
        }
    }
}
